package view;

import javax.swing.*;
import java.awt.*;
import model.Sale;
import dao.SaleDAO;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.DefaultTableCellRenderer;
import java.text.SimpleDateFormat;
import java.util.List;

public class SalesPanel extends JPanel {
    private JTable salesTable;
    private DefaultTableModel tableModel;
    private JTextField searchField;
    private JLabel totalLabel;
    private SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    
    public SalesPanel() {
        setLayout(new BorderLayout());
        
        // 工具面板
        JPanel toolPanel = new JPanel(new FlowLayout(FlowLayout.LEFT, 10, 5));
        searchField = new JTextField(20);
        JButton searchBtn = new JButton("搜索");
        JButton newSaleBtn = new JButton("新建销售");
        JButton refreshBtn = new JButton("刷新");
        
        toolPanel.add(new JLabel("图书名称："));
        toolPanel.add(searchField);
        toolPanel.add(searchBtn);
        toolPanel.add(newSaleBtn);
        toolPanel.add(refreshBtn);
        
        // 设置按钮样式
        styleButton(searchBtn);
        styleButton(newSaleBtn);
        styleButton(refreshBtn);
        
        add(toolPanel, BorderLayout.NORTH);
        
        // 初始化表格
        initTable();
        
        // 添加统计面板
        JPanel statsPanel = new JPanel(new FlowLayout(FlowLayout.LEFT));
        totalLabel = new JLabel("总金额：¥0.00");
        totalLabel.setFont(new Font("微软雅黑", Font.BOLD, 14));
        statsPanel.add(totalLabel);
        
        add(statsPanel, BorderLayout.SOUTH);
        
        // 添加事件监听
        searchBtn.addActionListener(e -> searchSales());
        newSaleBtn.addActionListener(e -> {
            SellDialog dialog = new SellDialog((JFrame) SwingUtilities.getWindowAncestor(this), this);
            dialog.setVisible(true);
        });
        refreshBtn.addActionListener(e -> refreshTable());
        
        // 添加搜索框回车事件
        searchField.addActionListener(e -> searchSales());
        
        // 初始加载数据
        refreshTable();
    }
    
    private void styleButton(JButton button) {
        button.setFont(new Font("微软雅黑", Font.PLAIN, 12));
        button.setFocusPainted(false);
        button.setBackground(new Color(59, 89, 152));
        button.setForeground(Color.WHITE);
        button.setBorder(BorderFactory.createEmptyBorder(5, 10, 5, 10));
    }
    
    private void initTable() {
        String[] columns = {"ID", "日期", "图书", "数量", "单价", "金额"};
        tableModel = new DefaultTableModel(columns, 0) {
            @Override
            public boolean isCellEditable(int row, int column) {
                return false;
            }
            
            @Override
            public Class<?> getColumnClass(int columnIndex) {
                if (columnIndex == 0 || columnIndex == 3) return Integer.class;
                if (columnIndex == 4 || columnIndex == 5) return Double.class;
                return String.class;
            }
        };
        
        salesTable = new JTable(tableModel);
        styleTable(salesTable);
        
        add(new JScrollPane(salesTable), BorderLayout.CENTER);
    }
    
    private void styleTable(JTable table) {
        table.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
        table.setRowHeight(25);
        table.getTableHeader().setReorderingAllowed(false);
        
        // 设置列宽
        table.getColumnModel().getColumn(0).setPreferredWidth(50);  // ID
        table.getColumnModel().getColumn(1).setPreferredWidth(150); // 日期
        table.getColumnModel().getColumn(2).setPreferredWidth(200); // 图书
        table.getColumnModel().getColumn(3).setPreferredWidth(80);  // 数量
        table.getColumnModel().getColumn(4).setPreferredWidth(100); // 单价
        table.getColumnModel().getColumn(5).setPreferredWidth(100); // 金额
        
        // 设置数字列右对齐
        DefaultTableCellRenderer rightRenderer = new DefaultTableCellRenderer();
        rightRenderer.setHorizontalAlignment(JLabel.RIGHT);
        table.getColumnModel().getColumn(3).setCellRenderer(rightRenderer);
        table.getColumnModel().getColumn(4).setCellRenderer(rightRenderer);
        table.getColumnModel().getColumn(5).setCellRenderer(rightRenderer);
        
        // 设置表格字体
        Font font = new Font("微软雅黑", Font.PLAIN, 14);
        table.setFont(font);
        table.getTableHeader().setFont(font);
        
        // 设置表格行高亮
        table.setSelectionBackground(new Color(184, 207, 229));
    }
    
    private void searchSales() {
        String keyword = searchField.getText().trim();
        SaleDAO dao = new SaleDAO();
        List<Sale> sales = dao.searchSales(keyword);
        updateTableData(sales);
    }
    
    public void refreshTable() {
        SaleDAO dao = new SaleDAO();
        List<Sale> sales = dao.getAllSales();
        updateTableData(sales);
    }
    
    private void updateTableData(List<Sale> sales) {
        tableModel.setRowCount(0);
        double total = 0;
        
        for (Sale sale : sales) {
            double unitPrice = sale.getTotalPrice() / sale.getQuantity();
            Object[] row = {
                sale.getId(),
                dateFormat.format(sale.getSaleDate()),
                sale.getBookTitle(),
                sale.getQuantity(),
                unitPrice,
                sale.getTotalPrice()
            };
            tableModel.addRow(row);
            total += sale.getTotalPrice();
        }
        
        totalLabel.setText(String.format("总金额：¥%.2f", total));
    }
} 